<template>
    <div class="box">
        <!-- 健康档案 -->
        <el-card>
            <template #header>
                <h3 class="title">{{ healthRecord.name }}的健康档案</h3>
            </template>
            <el-form :model="healthRecord" label-width="120px">
                <el-form-item label="姓名" prop="name">
                    <p v-text="healthRecord.name"></p>
                </el-form-item>
                <el-form-item label="身高" prop="height">
                    <p v-text="healthRecord.height + '（cm）'"></p>
                </el-form-item>
                <el-form-item label="体重" prop="weight">
                    <p v-text="healthRecord.weight + '（kg）'"></p>
                </el-form-item>
                <el-form-item label="血压" prop="healthRecord_name">
                    <p v-text="healthRecord.blood_pressure + '（mmHg）'"></p>
                </el-form-item>
                <el-form-item label="心率" prop="heart_rate">
                    <p v-text="healthRecord.heart_rate + '（bpm）'"></p>
                </el-form-item>
                <el-form-item label="体温" prop="temperature">
                    <p v-text="healthRecord.temperature + '（℃）'"></p>
                </el-form-item>
                <el-form-item label="血型" prop="blood_type">
                    <p v-text="healthRecord.blood_type"></p>
                </el-form-item>
                <el-form-item label="过敏原" prop="allergies">
                    <p v-text="healthRecord.allergies"></p>
                </el-form-item>
                <el-form-item label="慢性疾病信息" prop="chronic_conditions">
                    <p v-text="healthRecord.chronic_conditions"></p>
                </el-form-item>
                <el-form-item label="当前用药情况" prop="current_medications">
                    <p v-text="healthRecord.current_medications"></p>
                </el-form-item>
                <el-form-item label="饮食习惯" prop="dietary_habits">
                    <p v-text="healthRecord.dietary_habits"></p>
                </el-form-item>
                <el-form-item label="运动习惯" prop="exercise_routine">
                    <p v-text="healthRecord.exercise_routine"></p>
                </el-form-item>
                <el-form-item label="是否吸烟" prop="smoking_status">
                    <p v-if="healthRecord.smoking_status">是</p>
                    <p v-else>否</p>
                </el-form-item>
                <el-form-item label="是否饮酒" prop="alcohol_status">
                    <p v-if="healthRecord.alcohol_status">是</p>
                    <p v-else>否</p>
                </el-form-item>
                <el-form-item label="睡眠情况" prop="sleep_patterns">
                    <p v-text="healthRecord.sleep_patterns"></p>
                </el-form-item>
                <el-form-item label="免疫接种记录" prop="immunizations">
                    <p v-text="healthRecord.immunizations"></p>
                </el-form-item>
                <el-form-item label="心理健康状况" prop="mental_health">
                    <p v-text="healthRecord.mental_health"></p>
                </el-form-item>
                <el-form-item label="最近体检日期" prop="last_physical_exam">
                    <p v-text="healthRecord.last_physical_exam"></p>
                </el-form-item>
                <el-form-item label="备注" prop="notes">
                    <p v-text="healthRecord.notes"></p>
                </el-form-item>
                <!-- <el-form-item label="创建时间" prop="created_time">
                    <p v-text="healthRecord.created_time"></p>
                </el-form-item> -->
                <el-form-item label="修改时间" prop="updated_time">
                    <p v-text="healthRecord.updated_time"></p>
                </el-form-item>
            </el-form>
            <div class="analysis">
                <!-- BMI指数 -->
                <div v-if="BMI">
                    <el-tag type="primary" size="large" v-if="BMI < 18.5" v-text="'BMI指数：' + BMI + '（kg/㎡）'"></el-tag>
                    <el-tag type="success" size="large" v-else-if="BMI >= 18.5 && BMI < 24"
                        v-text="'BMI指数：' + BMI + '（kg/㎡）'"></el-tag>
                    <el-tag type="warning" size="large" v-else-if="BMI >= 24 && BMI < 28"
                        v-text="'BMI指数：' + BMI + '（kg/㎡）'"></el-tag>
                    <el-tag type="danger" size="large" v-else v-text="'BMI指数：' + BMI + '（kg/㎡）'"></el-tag>
                </div>
                <!-- 血压 -->
                <div v-if="healthRecord.blood_pressure">
                    <el-tag type="warning" size="large" v-if="systolic <= 90 || diastolic <= 60"
                        v-text="'血压：' + healthRecord.blood_pressure + '（mmHg）'"></el-tag>
                    <el-tag type="danger" size="large" v-else-if="systolic >= 140 || diastolic >= 90"
                        v-text="'血压：' + healthRecord.blood_pressure + '（mmHg）'"></el-tag>
                    <el-tag type="success" size="large" v-else
                        v-text="'血压：' + healthRecord.blood_pressure + '（mmHg）'"></el-tag>
                </div>
                <!-- 心率 -->
                <div v-if="healthRecord.heart_rate">
                    <el-tag type="primary" size="large" v-if="healthRecord.heart_rate <= 60"
                        v-text="'心率：' + healthRecord.heart_rate + '（bpm）'"></el-tag>
                    <el-tag type="danger" size="large" v-else-if="healthRecord.heart_rate >= 100"
                        v-text="'心率：' + healthRecord.heart_rate + '（bpm）'"></el-tag>
                    <el-tag type="success" size="large" v-else
                        v-text="'心率：' + healthRecord.heart_rate + '（bpm）'"></el-tag>
                </div>
                <!-- 体温 -->
                <div v-if="healthRecord.temperature">
                    <el-tag type="primary" size="large" v-if="healthRecord.temperature < 36"
                        v-text="'体温：' + healthRecord.temperature + '（℃）'"></el-tag>
                    <el-tag type="danger" size="large" v-else-if="healthRecord.temperature >= 37.3"
                        v-text="'体温：' + healthRecord.temperature + '（℃）'"></el-tag>
                    <el-tag type="success" size="large" v-else
                        v-text="'体温：' + healthRecord.temperature + '（℃）'"></el-tag>
                </div>
                <!-- 是否吸烟 -->
                <div v-if="healthRecord.smoking_status !== undefined">
                    <el-tag type="danger" size="large" v-text="'吸烟'" v-if="healthRecord.smoking_status"></el-tag>
                    <el-tag type="success" size="large" v-text="'不吸烟'" v-else></el-tag>
                </div>
                <!-- 是否饮酒 -->
                <div v-if="healthRecord.alcohol_status !== undefined">
                    <el-tag class="alcohol" type="danger" size="large" v-text="'饮酒'"
                        v-if="healthRecord.alcohol_status"></el-tag>
                    <el-tag type="success" size="large" v-text="'不饮酒'" v-else></el-tag>
                </div>
            </div>
        </el-card>
        <!-- 病历浏览态 -->
        <el-card v-if="show === 'browse'">
            <template #header>
                <h3 class="title">{{ medicalHistory.name }}的病历<span v-if="medicalHistory.id">（病历编号{{ medicalHistory.id
                }}）</span></h3>
            </template>
            <el-form :model="medicalHistory" label-width="120px">
                <el-form-item label="姓名" prop="name">
                    <p v-text="medicalHistory.name"></p>
                </el-form-item>
                <el-form-item label="医生" prop="name">
                    <p v-text="medicalHistory.doctor"></p>
                </el-form-item>
                <el-form-item label="问诊日期" prop="name">
                    <p v-text="medicalHistory.visit_date"></p>
                </el-form-item>
                <el-form-item label="主诉" prop="chief_complaint">
                    <p v-text="medicalHistory.chief_complaint"></p>
                </el-form-item>
                <el-form-item label="现病史" prop="present_illness">
                    <p v-text="medicalHistory.present_illness"></p>
                </el-form-item>
                <el-form-item label="既往病史" prop="past_medical_history">
                    <p v-text="medicalHistory.past_medical_history"></p>
                </el-form-item>
                <el-form-item label="手术历史" prop="past_surgical_history">
                    <p v-text="medicalHistory.past_surgical_history"></p>
                </el-form-item>
                <el-form-item label="诊断" prop="diagnosis">
                    <p v-text="medicalHistory.diagnosis"></p>
                </el-form-item>
                <el-form-item label="治疗方案" prop="treatment">
                    <p v-text="medicalHistory.treatment"></p>
                </el-form-item>
                <el-form-item label="医生备注" prop="notes">
                    <p v-text="medicalHistory.notes"></p>
                </el-form-item>
                <!-- <el-form-item label="修改人" prop="operator">
                    <p v-text="medicalHistory.operator"></p>
                </el-form-item>
                <el-form-item label="修改时间" prop="updated_time">
                    <p v-text="medicalHistory.updated_time"></p>
                </el-form-item> -->
            </el-form>
            <template #footer>
                <div class="history-footer">
                    <el-button type="primary" @click="showPastMedicalHistory()">查看患者过往病历</el-button>
                    <div>
                        <el-button type="primary" @click="show = 'edit'">修改</el-button>
                        <el-button type="success"
                            @click="this.$router.push('/prescription/' + medicalHistory.id)">开具处方</el-button>
                    </div>
                </div>
            </template>
        </el-card>
        <!-- 病历编辑态 -->
        <el-card v-if="show === 'edit'">
            <template #header>
                <h3 class="title">{{ medicalHistory.name }}的病历</h3>
            </template>
            <el-form :model="medicalHistory" label-width="120px" :rules="rules" ref="medicalHistoryForm">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="medicalHistory.name" disabled></el-input>
                </el-form-item>
                <el-form-item label="医生" prop="doctor">
                    <el-input v-model="medicalHistory.doctor" disabled></el-input>
                </el-form-item>
                <el-form-item label="问诊日期" prop="visit_date">
                    <el-date-picker v-model="medicalHistory.visit_date" type="date" value-format="YYYY-MM-DD"
                        disabled />
                </el-form-item>
                <el-form-item label="主诉" prop="chief_complaint">
                    <el-input v-model="medicalHistory.chief_complaint"></el-input>
                </el-form-item>
                <el-form-item label="现病史" prop="present_illness">
                    <el-input v-model="medicalHistory.present_illness" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="既往病史" prop="past_medical_history">
                    <el-input v-model="medicalHistory.past_medical_history" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="手术历史" prop="past_surgical_history">
                    <el-input v-model="medicalHistory.past_surgical_history" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="诊断" prop="diagnosis">
                    <el-input v-model="medicalHistory.diagnosis"></el-input>
                </el-form-item>
                <el-form-item label="治疗方案" prop="treatment">
                    <el-input v-model="medicalHistory.treatment" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="医生备注" prop="notes">
                    <el-input v-model="medicalHistory.notes"></el-input>
                </el-form-item>
                <!-- <el-form-item label="修改人" prop="operator">
                    <el-input v-model="medicalHistory.operator" disabled></el-input>
                </el-form-item>
                <el-form-item label="修改时间" prop="updated_time">
                    <el-date-picker v-model="medicalHistory.updated_time" type="datetime" format="YYYY-MM-DD HH:mm:ss"
                        disabled />
                </el-form-item> -->
            </el-form>
            <template #footer>
                <div class="history-footer">
                    <el-button type="primary" @click="showPastMedicalHistory()">查看患者过往病历</el-button>
                    <el-button v-if="add" type="primary" @click="addMedicalHistory()">生成病历</el-button>
                    <div v-else>
                        <el-button type="primary" @click="saveMedicalHistory()">保存</el-button>
                        <el-button @click="cancel()">取消</el-button>
                    </div>
                </div>
            </template>
        </el-card>
        <!-- 过往病历列表弹窗 -->
        <el-dialog v-model="showPastMedicalHistoryWindow" :width="dialogWidth" title="过往病历">
            <div class="history-list">
                <el-descriptions class="margin-top" :column="1" border label-width="140px">
                    <el-descriptions-item v-for="item in pastMedicalHistoryList">
                        <template #label>
                            <p class="cell-item">{{ item.visit_date }}</p>
                            <p>{{ item.institution }}</p>
                            <p>{{ item.department }}</p>
                            <p>{{ item.doctor }}</p>
                        </template>
                        <div class="history-item" @click="showPastMedicalHistoryDetail(item)">
                            <p class="history-item-title">主诉：{{ item.chief_complaint }}</p>
                            <p class="history-item-title">诊断：{{ item.diagnosis }}</p>
                            <p class="history-item-title">治疗方案：{{ item.treatment }}</p>
                        </div>
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </el-dialog>
        <!-- 病历详情弹窗 -->
        <el-dialog v-model="showPastMedicalHistoryDetailWindow" title="" :width="dialogWidth">
            <div class="history">
                <div class="title">
                    <h2 v-text="curMedicalHistory.institution" class="p1"></h2>
                    <h1 v-text="'门诊病历'" class="p2"></h1>
                </div>
                <div class="title-info">
                    <div class="info_column">
                        <div class="info-item">
                            <span class="label">编号</span>：
                            <span class="value" v-text="curMedicalHistory.id"></span>
                        </div>
                        <div class="info-item">
                            <span class="label">姓名</span>：
                            <span class="value" v-text="curMedicalHistory.name"></span>
                        </div>
                    </div>
                    <div class="info_column">
                        <div class="info-item">
                            <span class="label">性别</span>：
                            <span class="value" v-if="curMedicalHistory.gender == 1">男</span>
                            <span class="value" v-else>女</span>
                        </div>
                        <div class="info-item">
                            <span class="label">年龄</span>：
                            <span class="value" v-text="curMedicalHistory.age"></span>
                        </div>
                    </div>
                    <div class="info_column">
                        <div class="info-item">
                            <span class="label">科室</span>：
                            <span class="value" v-text="curMedicalHistory.department"></span>
                        </div>
                        <div class="info-item">
                            <span class="label">证件</span>：
                            <span class="value" v-text="curMedicalHistory.id_card"></span>
                        </div>
                    </div>
                </div>
                <hr>
                <div class="history-content">
                    <div class="content-item">
                        <span class="label">主诉</span>：
                        <span class="value" v-text="curMedicalHistory.chief_complaint"></span>
                    </div>
                    <div class="content-item">
                        <span class="label">现病史</span>：
                        <span class="value" v-text="curMedicalHistory.present_illness"></span>
                    </div>
                    <div class="content-item">
                        <span class="label">既往病史</span>：
                        <span class="value" v-text="curMedicalHistory.past_medical_history"></span>
                    </div>
                    <div class="content-item">
                        <span class="label">手术历史</span>：
                        <span class="value" v-text="curMedicalHistory.past_surgical_history"></span>
                    </div>
                    <div class="content-item">
                        <span class="label">诊断</span>：
                        <span class="value" v-text="curMedicalHistory.diagnosis"></span>
                    </div>
                    <div class="content-item">
                        <span class="label">治疗方案</span>：
                        <span class="value" v-text="curMedicalHistory.treatment"></span>
                    </div>
                    <div class="content-item">
                        <span class="label">医生备注</span>：
                        <span class="value" v-text="curMedicalHistory.notes"></span>
                    </div>
                </div>
                <div class="doctor">
                    <div class="item">
                        <span>医生</span>：
                        <span v-text="curMedicalHistory.doctor"></span>
                    </div>
                    <div class="item">
                        <span>日期</span>：
                        <span v-text="curMedicalHistory.visit_date"></span>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { healthRecordFindByResidentIdAPI } from '@/api/healthRecord';
import { medicalHistoryAddAPI, medicalHistoryFindByAppointmentIdAPI, medicalHistoryListFindByResidentIdAPI, medicalHistoryUpdateAPI } from '@/api/medicalHistory';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';

export default {
    data() {
        return {
            params: {
                // 查询参数
                resident_id: this.$route.params.id,
                department_id: '',
                // 分页参数
                total: 0,
                currentPage: 1,
                pageSize: 7,
            },
            healthRecord: {},
            BMI: '',
            systolic: '',
            diastolic: '',
            medicalHistory: {
                name: '',
                resident_id: this.$route.params.id,
                doctor: JSON.parse(sessionStorage.getItem('user')).name,
                // 自动获取当前日期
                visit_date: dayjs().format('YYYY-MM-DD'),
                chief_complaint: '',
                present_illness: '',
                past_medical_history: '',
                past_surgical_history: '',
                diagnosis: '',
                treatment: '',
                notes: '',
                operator: '',
                updated_time: '',
                appointment_id: ''
            },
            show: 'edit',
            add: true,
            rules: {
                // 从主诉到医生备注
                chief_complaint: { required: true, message: '请输入主诉', trigger: 'blur' },
                present_illness: { required: true, message: '请输入现病史', trigger: 'blur' },
                past_medical_history: { required: true, message: '请输入既往病史', trigger: 'blur' },
                past_surgical_history: { required: true, message: '请输入手术历史', trigger: 'blur' },
                diagnosis: { required: true, message: '请输入诊断', trigger: 'blur' },
                treatment: { required: true, message: '请输入治疗方案', trigger: 'blur' }
            },
            showPastMedicalHistoryWindow: false,
            showPastMedicalHistoryDetailWindow: false,
            pastMedicalHistoryList: [],
            curMedicalHistory: {}
        }
    },
    methods: {
        loadHealthRecord() {
            healthRecordFindByResidentIdAPI(this.$route.params.id).then((resp) => {
                if (resp.data.code == 2000) {
                    this.healthRecord = resp.data.data;
                    this.medicalHistory.name = this.healthRecord.name;
                    // 计算BMI指数
                    if (this.healthRecord.weight && this.healthRecord.height) {
                        this.BMI = (this.healthRecord.weight / Math.pow(this.healthRecord.height / 100, 2)).toFixed(1);
                    }
                    // 分解血压
                    if (this.healthRecord.blood_pressure) {
                        const [systolic, diastolic] = this.healthRecord.blood_pressure.split('-').map(Number);
                        // 收缩压（高压）
                        this.systolic = systolic;
                        // 舒张压（低压）
                        this.diastolic = diastolic;
                    }
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        loadMedicalHistory() {
            medicalHistoryFindByAppointmentIdAPI(this.medicalHistory.appointment_id).then((resp) => {
                if (resp.data.code == 2000) {
                    this.medicalHistory = resp.data.data;
                    this.add = false;
                    this.show = 'browse';
                } else {
                    if (resp.data.message != "暂无该次病历") {
                        ElMessage.error(resp.data.message);
                    }
                }
            })
        },
        addMedicalHistory() {
            this.$refs.medicalHistoryForm.validate((val) => {
                if (val) {
                    // 自动获取当前日期赋值给visit_date
                    this.medicalHistory.visit_date = new Date().toLocaleDateString();
                    this.medicalHistory.doctor_id = JSON.parse(sessionStorage.getItem('user')).user_id;
                    this.medicalHistory.institution_id = JSON.parse(sessionStorage.getItem('user')).institution_id;
                    this.medicalHistory.update_user = JSON.parse(sessionStorage.getItem('user')).user_id;
                    medicalHistoryAddAPI(this.medicalHistory).then((resp) => {
                        if (resp.data.code == 2000) {
                            this.loadMedicalHistory();
                            this.show = 'browse';
                            ElMessage.success(resp.data.message);
                        } else {
                            if (resp.data.message == "请先返回确认开始问诊") {
                                ElMessage.warning(resp.data.message);
                            } else {
                                ElMessage.error(resp.data.message);
                            }
                        }
                    })
                }
            })
        },
        saveMedicalHistory() {
            this.$refs.medicalHistoryForm.validate((val) => {
                if (val) {
                    // 自动获取当前日期赋值给visit_date
                    this.medicalHistory.visit_date = new Date().toLocaleDateString();
                    this.medicalHistory.doctor_id = JSON.parse(sessionStorage.getItem('user')).user_id;
                    this.medicalHistory.update_user = JSON.parse(sessionStorage.getItem('user')).user_id;
                    medicalHistoryUpdateAPI(this.medicalHistory).then((resp) => {
                        if (resp.data.code == 2000) {
                            this.loadMedicalHistory();
                            this.show = 'browse';
                            ElMessage.success(resp.data.message);
                        } else {
                            ElMessage.error(resp.data.message);
                        }
                    })
                }
            })
        },
        cancel() {
            this.loadMedicalHistory();
            this.show = 'browse';
        },
        showPastMedicalHistory() {
            medicalHistoryListFindByResidentIdAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.pastMedicalHistoryList = resp.data.datas;
                    this.showPastMedicalHistoryWindow = true;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        showPastMedicalHistoryDetail(item) {
            this.showPastMedicalHistoryDetailWindow = true;
            this.curMedicalHistory = item;
        }
    },
    created() {
        this.medicalHistory.appointment_id = localStorage.getItem('appointmentId');
        this.loadHealthRecord();
        this.loadMedicalHistory();
    }
}
</script>

<style scoped>
.box {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
}

.el-card {
    width: 630px;
    position: relative;
    /* 实现滚动 */
    /* overflow: auto; */
    /* 隐藏滚动条同时保留滚动功能 */
    -ms-overflow-style: none;
    /* IE and Edge */
    scrollbar-width: none;
    /* Firefox */
    overflow-y: scroll;
    /* 启用纵向滚动 */
}

.el-card .title {
    /* position: fixed; */
    text-align: center;
}

.analysis {
    position: fixed;
    left: 650px;
    top: 150px;
    width: 180px;
    display: flex;
    flex-direction: column;
    align-items: start;
    z-index: 999;
}

.analysis div {
    width: 100%;
}

.analysis .el-tag {
    width: 100%;
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 5px;
    justify-content: start;
}

.history-footer {
    display: flex;
    justify-content: space-between;
}

.history-item {
    align-items: center;
    padding: 10px;
    cursor: pointer;
    transition: all .2s;

    &:hover {
        background-color: #eee;
    }
}

.history {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.history .title {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 30%;
}

.history .title .p1 {
    width: 100%;
    text-align: justify;
    text-align-last: justify;
    white-space: nowrap;
}

.history .title .p2 {
    font-size: 30px;
    width: 80%;
    text-align: justify;
    text-align-last: justify;
    white-space: nowrap;
}

.history .title-info {
    width: 85%;
    display: flex;
    justify-content: center;
    align-items: center;
    white-space: nowrap;
}

.history .title-info .info_column {
    flex: 1;
}

.history .title-info .info_column .info-item {
    display: flex;
}

.history .title-info .info_column .info-item .label,
.history .history-content .content-item .label {
    width: 60px;
    text-align: justify;
    text-align-last: justify;
    white-space: nowrap;
}

.history .history-content {
    display: flex;
    flex-direction: column;
    width: 85%;
}

.history .history-content .content-item {
    margin: 5px 0 0 50px;
    display: flex;
}

.history .doctor {
    width: 100%;
    margin: 20px 50px 0 0;
    display: flex;
    justify-content: end;
}

.history .doctor .item {
    margin-left: 50px;
}

.history hr {
    width: 95%;
    border: #555 1px solid;
}
</style>